package com.yj.suncity.activity.shouye;

import java.util.List;

import org.json.JSONObject;

import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.bean.SuperadvListBean;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.ThreadUtils;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.async.ThreadUtils.OnResultListener;
import com.yj.suncity.bean.GoodsBean;
import com.yj.suncity.bean.GoodsListBean;
import com.yj.suncity.bean.GoodsShopBean;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.PullToRefreshView;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.DialogUtils.ReshActivity;
import com.yj.suncity.utis.PullToRefreshView.OnFooterRefreshListener;
import com.yj.suncity.utis.PullToRefreshView.OnHeaderRefreshListener;
import com.yj.suncity.viewpager.ViewPagerScrollSuperadv;
import com.yj.suncity.viewpager.ViewPagerScrollSuperadv.OnPagerClick;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ShopGoodsListActivity extends Activity implements
		OnHeaderRefreshListener, OnFooterRefreshListener {

	private Context context;
	private ListView mListView;
	private ViewPager pager;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private LinearLayout lay_view_select;
	private int mWidth;
	private ViewPagerScrollSuperadv scrollSuperadv;
	private String cityId;
	private String userId;
	private String titleName;
	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();

	private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
	private boolean mRefreshFlag = false;// 判断是否刷新
	private PullToRefreshView mPullToRefreshView = null;
	private int pageNum = 1;
	private DigouShopAdapter adapter;
	private List<GoodsShopBean> detailInfos;
	private int flag;// 首页->当前

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_digou_shop);
		context = this;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				//.displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		mWidth = getResources().getDisplayMetrics().widthPixels;
		cityId = preferencesUtil.getString(context, ShareCon.CITYFILE,
				ShareCon.CITYID, "140881");
		userId = getIntent().getStringExtra("userid");
		titleName = getIntent().getStringExtra("titlename");
		if (userId==null) {
			userId="";
		}
		
		findView();
		initData(1);
		
		//	getDg();// 从首页跳转过来得加超广告请求数据
		
	}

	private void findView() {
		((TextView) findViewById(R.id.txt_title_name)).setText(titleName);

		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);

		mListView = (ListView) findViewById(R.id.list_view_digou);
		TextView emptyView = (TextView) findViewById(R.id.txt_empty);
		mListView.setEmptyView(emptyView);

		if (flag == 1) {// 从首页跳转过来得加超广告
			View view = LayoutInflater.from(context).inflate(
					R.layout.view_page, null);
			lay_view_select = (LinearLayout) view
					.findViewById(R.id.lay_view_select);
			RelativeLayout layout = (RelativeLayout) view
					.findViewById(R.id.lay_view_page);
			layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
					(int) (mWidth / 3)));
			pager = (ViewPager) view.findViewById(R.id.view_pager);
			mListView.addHeaderView(view);
		}
	}

	private void initData(int indext) {
		String path = URLCon.商品
					+ "?action=get_mygoods_list&pagesize=20&pageindex=" + indext
					+ "&cityid=" + cityId + "&releasetype=0&userid=" + userId;
		Log.d("", "抵购商品列表="+path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null,
				mPullToRefreshView, mRefreshFlag, null, true, "正在加载......",
				new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						GoodsListBean listBean = new GoodsListBean(jsonObject);
						pageNum = Integer.valueOf(listBean.getTotalpage());
						if (mRefreshHeadFlag) {
							adapter = null;
						}
						if (adapter == null) {
							detailInfos = listBean.getShopData();
							adapter = new DigouShopAdapter(detailInfos);
							mListView.setAdapter(adapter);
						} else {
							detailInfos.addAll(listBean.getShopData());
							adapter.notifyDataSetChanged();
						}
					}
				});
		asyncTaskUtil.execute(path);
	}

	private void getDg() {
		String path = URLCon.超广广告 + "?action=superadvlist&cityid=" + cityId
				+ "&type=5";
		Log.d("", "超广广告=" + path);
		ThreadUtils threadUtils = new ThreadUtils();
		threadUtils.startThread(path, new OnResultListener() {
			@Override
			public void jsonResult(JSONObject json) {
				SuperadvListBean listBean = new SuperadvListBean(json);
				scrollSuperadv = new ViewPagerScrollSuperadv(context,
						imageLoader, options, pager, lay_view_select, listBean
								.getData(), new OnPagerClick() {
							@Override
							public void onPagerClick(String advid,
									String adv_userid) {
								 Intent intent = new Intent(context,
								 SeeAdvDetailActivity.class);
								 intent.putExtra("adv_userid", adv_userid);
								 intent.putExtra("advid", advid);
								 intent.putExtra("flag", 2);
								 startActivity(intent);

							}
						});

			}
		});
	}

	@Override
	protected void onResume() {
		if (scrollSuperadv != null) {
			scrollSuperadv.startTimer();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (scrollSuperadv != null) {
			scrollSuperadv.stopTimer();
		}
		super.onPause();
	}
	
	class DigouShopAdapter extends BaseAdapter {
		private List<GoodsShopBean> shopBeans;

		public DigouShopAdapter(List<GoodsShopBean> shopBeans) {
			super();
			this.shopBeans = shopBeans;
		}

		@Override
		public int getCount() {
			return shopBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return shopBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = getLayoutInflater().inflate(
						R.layout.adapter_goods_shop_item, null);
				holder.mLay_rela_shop_name = (RelativeLayout) convertView
						.findViewById(R.id.lay_rela_shop_name);
				if (!userId.equals("")) {
					holder.mLay_rela_shop_name.setVisibility(View.GONE);
				}
				holder.mList_goods = (ListView) convertView
						.findViewById(R.id.list_view_goos_item);
				holder.mTxt_shop_name = (TextView) convertView
						.findViewById(R.id.txt_shop_name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final GoodsShopBean shopBean = shopBeans.get(position);
			holder.mTxt_shop_name.setText(shopBean.getEntname());
			holder.mList_goods.setAdapter(new DigouAdapter(shopBean.getGoods()));
			holder.mLay_rela_shop_name.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent=new Intent(context, SeeAdvDetailActivity.class);
					intent.putExtra("adv_userid", shopBean.getUserid());
					intent.putExtra("advid", "");
					intent.putExtra("flag", 2);
					startActivity(intent);
				}
			});
			return convertView;
		}
	}

	class DigouAdapter extends BaseAdapter {
		private List<GoodsBean> goodsBeans;

		public DigouAdapter(List<GoodsBean> goodsBeans) {
			super();
			this.goodsBeans = goodsBeans;
		}

		@Override
		public int getCount() {
			return goodsBeans.size();
		}

		@Override
		public Object getItem(int position) {
			return goodsBeans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_goods_item, null);
				holder.mImg_logo = (ImageView) convertView
						.findViewById(R.id.img_logo);
				holder.mTxt_name = (TextView) convertView
						.findViewById(R.id.txt_name);
				holder.mTxt_num = (TextView) convertView
						.findViewById(R.id.txt_digou_num);
				holder.mTxt_silver_num = (TextView) convertView
						.findViewById(R.id.txt_silver_num);
				holder.mLay_linear_goods = (LinearLayout) convertView
						.findViewById(R.id.lay_linear_goods);
				holder.mTxt_silver_money = (TextView) convertView
						.findViewById(R.id.txt_silver_money);
				holder.mTxt_silver_type = (TextView) convertView
						.findViewById(R.id.txt_silver_type);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final GoodsBean goodsBean = goodsBeans.get(position);
			holder.mTxt_name.setText(goodsBean.getGoods_title());
			holder.mTxt_num.setText(goodsBean.getGood_num());
			holder.mTxt_silver_num.setText(goodsBean.getSilver_num());
			
			if (goodsBean.getSilver_money().equals("0")) {
				holder.mTxt_silver_type.setText("现金：");
				holder.mTxt_silver_money.setText("元");
			} else {
				holder.mTxt_silver_type.setText("现金：");
				holder.mTxt_silver_money.setText("元");
			}
			
			
			
			
			

			if (!goodsBean.getImg_url().equals("")) {
				if (goodsBean.getImg_url().contains(",")) {
					imageLoader.displayImage(
							URLCon.HOST
									+ (goodsBean.getImg_url().split(","))[0],
							holder.mImg_logo, options);
				}else{
					imageLoader.displayImage(
							URLCon.HOST+goodsBean.getImg_url(),
							holder.mImg_logo, options);
				}
			} else {
				holder.mImg_logo
						.setImageResource(R.drawable.android_layout_detail);
			}
			holder.mLay_linear_goods.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (goodsBean.getRelease_type().equals("2")) {//
						flag=1;
					}else{
						flag=2;
					}
					Intent intent = new Intent(context,
							ProductDateilsActivity.class);
					intent.putExtra("goodid", goodsBean.getId());
					intent.putExtra("flag", flag);
					startActivity(intent);

				}
			});
			if (!userId.equals("")) {
				holder.mLay_linear_goods
						.setOnLongClickListener(new OnLongClickListener() {
							@Override
							public boolean onLongClick(View v) {
								DialogUtils dialogUtils = DialogUtils
										.getInstance();
								dialogUtils.backDialog(context, "确定删除此商品吗？",
										true, new ReshActivity() {
											@Override
											public void reshActivity() {
												deleteDigou(goodsBean.getId());
											}
										});

								return false;
							}
						});
			}
			return convertView;
		}
	}

	class ViewHolder {
		ImageView mImg_logo;
		TextView mTxt_name;
		TextView mTxt_num;
		TextView mTxt_silver_num;
		LinearLayout mLay_linear_goods;
		TextView mTxt_silver_type;
		TextView mTxt_silver_money;

		RelativeLayout mLay_rela_shop_name;
		ListView mList_goods;
		TextView mTxt_shop_name;
	}

	// 删除抵购商品
	private void deleteDigou(String goodsId) {
		String path = URLCon.发布商品 + "?action=delgoods&userid=" + userId
				+ "&id=" + goodsId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, null, true, "正在删除......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						if (jsonObject.optString("success").equals("1")) {
							mRefreshHeadFlag = true;// 判断是否刷新的是头部(刚开始默认是头部刷新)
							mRefreshFlag = false;// 判断是否刷新
							indexPage = 1;
							initData(indexPage);
						} else {
							ToastUtil.ShowToast(context,
									jsonObject.optString("msg"));
						}

					}
				});
		asyncTaskUtil.execute(path);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnHeadBack:
			this.finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = false;
				mRefreshFlag = true;

				++indexPage;
				if (indexPage > pageNum) {
					ToastUtil.ShowToast(context, "没有更多数据！");
					mPullToRefreshView.onFooterRefreshComplete();
					return;
				} else {
					initData(indexPage);
				}

				// mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1);

	}

	int indexPage = 1;

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mRefreshHeadFlag = true;
				mRefreshFlag = true;
				// if (async != null) {
				// Utils.cancelTaskInterrupt(async);
				// async = null;
				// }
				indexPage = 1;// 刷新头部时将页数初始化为1
				initData(indexPage);
				// mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1);
	}

}
